package com.tianyadu.security.browser.controller;

import com.tianyadu.security.browser.common.SimpleResponse;
import com.tianyadu.security.browser.common.SocialUserInfo;
import com.tianyadu.security.core.properties.SecurityProperties;
import com.tianyadu.security.core.properties.propertieVO.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @FileName: BrowserSecurityController
 * @Description:
 * @author: xueyj
 * @create: 2018-12-06 17:17
 */
@RestController
@Slf4j
public class BrowserSecurityController {

    /** 获取HttpSessionRequest缓存信息 */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /** 获取security中请求重定向Strategy */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /** 获取security配置信息 */
    @Autowired
    private SecurityProperties securityProperties;

    /** 社交登陆工具类 */
    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
      * @Description: 用户授权认证
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/10 10:31
      */
    @RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //  获取引发跳转请求信息
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            //  获取引发跳转的请求
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是:【{}】", targetUrl);
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                String loginPage = securityProperties.getBrowser().getLoginPage();
                redirectStrategy.sendRedirect(request, response, loginPage);
            }
        }
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }

    @GetMapping("/social/user")
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        SocialUserInfo userInfo = new SocialUserInfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        //  用户社交平台id（QQ/微信）
        userInfo.setProviderId(connection.getKey().getProviderId());
        //  用户openid
        userInfo.setProviderUserId(connection.getKey().getProviderUserId());
        //  用户昵称
        userInfo.setNickname(connection.getDisplayName());
        //  用户头像
        userInfo.setHeadimg(connection.getImageUrl());
        return userInfo;
    }
}